'use strict';

/* 
	产品列表
*/
var React = require('react-native');

var {
	StyleSheet,
	Text,
	View,
	Image,
	TouchableOpacity,
	ListView,
	ToastAndroid,
	InteractionManager
} = React;

module.exports = React.createClass({

	getInitialState: function() {

		return {
			itemWidth: null,
			productList: null,
		};
	},

	componentWillMount: function() {

	},

	componentDidMount: function() {

		InteractionManager.runAfterInteractions(this.loadProductList);
	},

	render: function() {

		var body = null;
		if (this.state.itemWidth && this.state.productList) {
			body = this.state.productList.items.map(this.renderProduct);
		}

		return (
			<View style={styles.container} onLayout={this.calcWidth}>
				{body}
			</View>
		);
	},

	renderProduct: function(product) {

		var imgUrl = 'http://img14.360buyimg.com/n2/s410x410_' + product.imagePath;
		var price = '￥' + (parseFloat(product.price) / 100).toFixed(2);

		return (
			<TouchableOpacity style={[styles.product,{width: this.state.itemWidth}]} >
				<Image style={styles.productImage} source={{uri:imgUrl}}></Image>
				<Text style={styles.productTitle} numberOfLines={2}>{product.name}</Text>
				<Text style={styles.productPrice}>{price}</Text>
			</TouchableOpacity>
		)
	},

	calcWidth: function(e) {

		//ToastAndroid.show('width: ' + e.nativeEvent.layout.width, ToastAndroid.SHORT);

		var itemWidth = e.nativeEvent.layout.width / 2 - 5;

		if (Math.abs(this.state.itemWidth || 0 - itemWidth) > 1) {
			this.setState({
				itemWidth: itemWidth
			})
		}
	},
	loadProductList: function() {

		var self = this;

		fetch('http://wyx.m.jd.com/product/rest/channelProducts.htm?cid=1343&level=2&keyword=毛呢大衣&page=1&pageSize=20&orderBy=0&direction=0')
			.then((response) => response.json())
			.then((res) => {
				self.setState({
					productList: res.data
				})
			})
			.catch((error) => {
				console.warn(error);
			});
	}

});

var styles = StyleSheet.create({
	container: {
		flex: 1,
		flexDirection: 'row',
		flexWrap: 'wrap',
		justifyContent: 'space-around',
		paddingBottom: 15
	},
	product: {
		marginTop: 5,
		backgroundColor: '#FFF',
	},
	productImage: {
		height: 220
	},
	productTitle: {
		fontSize: 18,
	},
	productPrice: {
		fontSize: 18,
		color: 'red',
	}
});